﻿using System;
using System.IO;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using API;
using Foundation;
using mb;
using mb.iOS;
using Masonry;
using UIKit;

namespace libmp
{
    /*
    注意：
    所有在hotfix里的UIViewController子类，都存在一个问题：ViewDidLoad回调会错过！
    原因是，这个虚函数尽然是在构造函数里调用，这本身违反了面向对象设计模式的准则

    其实际影响则是：
    由于这hotfix里的类都是通过ilruntime解释执行，其在clr层面真实类型是相应的adaptor类，
    它的实例在构造时，ILTypeInstance instance属性是在构造函数中赋值，ViewDidLoad则是在基类构造函数里调用，
    而基类构造函数先于本类的构造体运行，所以当调到ViewDidLoad时，adaptor类的instance属性还未赋值，
    所以根本无法取得ilr脚本类里的重载函数进行调用了，这一点ilruntime自身示例都未考虑到，当然这不是ilruntime的问题，
    而是xamarin.ios封装的问题（也可能是ios本身的问题），违反了不在构造函数里调虚函数的原则。

    所以解决办法是：
    在构造函数中自己发起一个延时调用，如用await去延时，确保构造函数执行完后再调用ViewDidLoad
    
     */
    public class VCMain : UITabBarController
    {
        static ILog logger = App.logger;
        int lastSelectedIndex = -1;

        public VCMain()
        {
            Xinit();
        }

        async void Xinit()
        {
            await Task.Delay(1);

            ViewDidLoad();
        }

        public override void ViewDidLoad()
        {
            // base.ViewDidLoad();
            // logger.Log("VCMain ViewDidLoad", View.Frame);
            InitSubViews();
        }

        void InitSubViews()
        {
            var so = mb.ServiceLocator.Instance.Get<IStartOption>();
            var vctest = so.GetBoolValue("vctest");

            var icons = new string[] { "Home", "Classification", "Receive", "PersonalCenter" };
            var vcs = new UIViewController[]
            {
                new VCHome(),
                new VCCategory(),
                new VCMemberCenterController(),
                //new VCShop(),
                new VCSetting(),
            };
            if (vctest)
            {
                icons = icons.Append("Test").ToArray();
                vcs = vcs.Append(new VCTest()).ToArray();
            }

            this.ViewControllers = vcs;
            for (int i = 0; i < icons.Length; i++)
            {
                var img = UIImage.FromFile($"{App.HotStorageRoot}/res/maintab/{icons[i]}.png");
                var rimg = new UIImage(img.CGImage, 2, UIImageOrientation.Up);
                TabBar.Items[i].Image = rimg;
            }
            TabBar.TintColor = Util.MainColor;
            ViewControllerSelected += this.OnSelect;

            var dt = so.GetStringValue("defaulttab");
            if (dt != null) OpenPage(dt);
        }

        int GetVCIndex(UIViewController vc)
        {
            for (int i = 0; i < ViewControllers.Length; i++)
            {
                if (ViewControllers[i] == vc)
                    return i;
            }
            return -1;
        }

        void OnSelect(object obj, UITabBarSelectionEventArgs e)
        {
            int index = GetVCIndex(e.ViewController);
            logger.Log("tabselect", index, this.lastSelectedIndex);

            if (index == this.lastSelectedIndex)
                this.CallReClick(e.ViewController);

            this.lastSelectedIndex = index;
        }

        void CallReClick(UIViewController vc)
        {
            vc.GetType().GetMethod("ReClick")?.Invoke(vc, null);
        }

        void OpenPage(string name)
        {
            logger.Log("open page", name);
            if (name == "movie")
            {
                var vi = DataStore.store.GetAllVideo() [0];
                AppDelegate.Instance.NavController.PushViewController(new VCMoviePlayer(vi), false);
            }
            else if (name == "offlineCache")
            {
                AppDelegate.Instance.NavController.PushViewController(new VCOfflineCacheController(), false);
            }
            else
            {
                try
                {
                    this.SelectedIndex = int.Parse(name);
                }
                catch (Exception e) { }
                finally { }
            }
        }
    }
}